package cu.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/*
        目标：切面类
        Aspect:标识此类为切面类
 */
@Aspect
@Component
public class LogAspect {
    /**
     * Before:前置通知,目标方法执行之前需要执行的方法;
     * 1.JoinPoint参数：连接点对象,即:需要执行的目标方法对象;
     */
    @Before(value = "execution(public int cu.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        /*
            1.getSignature():获取目标方法签名;
            2.getName():获取目标方法的方法名;
            3.getArgs():获取目标方法参数列表;
         */
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("1.LogAspect.beforeMethod:" + name + "方法开始了、、、参数为：" + args);
    }

    @After(value = "execution(public int cu.tedu._07springaop.aop.CalculatorImpl.*(..)))")
    public void afterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("3.后置通知：" + name + "方法执行结束了");
    }

    @AfterReturning(value = "execution(public int cu.tedu._07springaop.aop.CalculatorImpl.*(..)))", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("2.返回通知：" + name + "正常结束,结果为：" + result);

    }

    @AfterThrowing(value = "execution(public int cu.tedu._07springaop.aop.CalculatorImpl.*(..)))", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex) {

        System.out.println("异常通知：目标方法抛出异常，异常信息为：" + ex.getMessage());
    }


    @Around(value = "execution(public int cu.tedu._07springaop.aop.CalculatorImpl.*(..)))")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) {
        Object result = null;

        try {
            System.out.println("111.前置通知");
            result = proceedingJoinPoint.proceed();//执行目标方法
            System.out.println("222.返回通知");
        } catch (Throwable e) {

            System.out.println("333.异常通知");
        } finally {
            System.out.println("444.后置通知");
        }
        return result;

    }

}
